package com.example.test15middleware.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: fxy
 * @Date: 2022/07/08/11:09
 * @Description:
 */
@Service
public class JedisGenerator {


    public String getNo(String key,String pre){
        Jedis jedis1 = new Jedis("127.0.0.1", 6379);
        if(StringUtils.isEmpty(pre)){
            pre = "";
        }
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        if(!jedis1.get(key+"date").equals(date)){
            jedis1.set(key+"date",date);
        }
        Long no;
        String val = null;
        try {
            while(true){
                jedis1.watch(key);
                Transaction multi = jedis1.multi();
                multi.incr(key);
                Response<String> stringResponse = multi.get(key);
                val = stringResponse.get();
                no = Long.valueOf(stringResponse.get());
                List list = multi.exec();
                if (list != null && list.size() > 0) {
                    System.out.println("自增成功：当前值="+stringResponse.get());
                    break;
                }else {//执行结果不是OK，说明被修改了，被别人抢了
                    System.out.println("自增失败");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            jedis1.close();
        }
        return val;
    }

    private String formatInt(Long value) {
        DecimalFormat df = new DecimalFormat("000000");
        return df.format(value);
    }

}
